package com.tim.wicket.examples.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import com.tim.wicket.examples.model.Cheese;

public class CheesePropertyReader {

	private Properties cheeseProperties;
	
	public CheesePropertyReader(InputStream cheeseStream) throws IOException {
		this.cheeseProperties = new Properties();
		this.cheeseProperties.load(cheeseStream);
	}
	
	public List<Cheese> readCheeses() {
		List<Cheese> cheeses = new ArrayList<Cheese>();
		
		Enumeration<?> properties = cheeseProperties.propertyNames();
		while (properties.hasMoreElements()) {
			String key = properties.nextElement().toString();
			
			if (!key.endsWith("name")) {
				continue;
			}
			
			String prefix = key.substring(0, key.indexOf("."));
			
			String name = cheeseProperties.getProperty(prefix + ".name");
			String description = cheeseProperties.getProperty(prefix + ".description");
			String price = cheeseProperties.getProperty(prefix + ".price");
			
			cheeses.add(new Cheese(name, description, Double.parseDouble(price)));
		}
		
		return cheeses;
	}

}
